package com.itheima.filter;


import com.itheima.utils.CurrentHolder;
import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;

import java.io.IOException;

@Slf4j
@WebFilter(urlPatterns = "/*")
public class TokenFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        String path = req.getRequestURI();
        log.info("请求路径：{}", path);
        if (path.endsWith("/login")) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        String token = req.getHeader("Token");
        log.info(token);
        if (StringUtils.hasText(token)) {
            try {
                Claims claims = JwtUtils.parseJWT(token);
                Integer empId = claims.get("id", Integer.class);
                CurrentHolder.setCurrentId(empId);
                log.info("用户的信息为：{}", claims);
                filterChain.doFilter(servletRequest, servletResponse);
                return;
            } catch (Exception e) {
                log.error("解析token失败", e);
            } finally {
                //使用后要移除，防止内存泄漏
                CurrentHolder.remove();
            }
        }
        HttpServletResponse res = (HttpServletResponse) servletResponse;
        // 设置状态码为401，用户没有登录
        res.setStatus(HttpStatus.UNAUTHORIZED.value());
    }
}
